744A - Hongcow Builds A Nation - CodeForces Solution


dfs and similar graphs *1500

Please click on ads to support us..

Python Code:

from collections import deque
n, m, k=[int(v) for v in input().split()]
w=[int(v) for v in input().split()]
iota=[]
q={}
for j in range(m):
    iota.append([int(v) for v in input().split()])
    if iota[-1][0] in q:
        q[iota[-1][0]].append(iota[-1][1])
    else:
        q[iota[-1][0]]=[iota[-1][1]]
    if iota[-1][1] in q:
        q[iota[-1][1]].append(iota[-1][0])
    else:
        q[iota[-1][1]]=[iota[-1][0]]
check=set(w)
rho=[]
for j in w:
    new=deque([j])
    res=1
    while new:
        x=new.pop()
        if j in q:
            for j in q[x]:
                if j not in check:
                    new.appendleft(j)
                    check.add(j)
                    res+=1
    rho.append(res)
res=0
rho.sort()
epsilon=n-sum(rho)
zeta=rho.pop()+epsilon
for j in rho:
    res+=j*(j-1)//2
res+=zeta*(zeta-1)//2
print(res-m)

C++ Code:

#include<bits/stdc++.h>
#pragma GCC optimize("O3")
#define mod 1000000007
#define fi first
#define se second
using namespace std;
int n,sz[1002],fr,m,k;
int ed[1002];
vector<int>gov;
vector<int>v[1002];
int cc;
bool viz[1002];
void dfs(int nod)
{
    ++sz[cc];
    viz[nod]=1;
    for(int i=0;i<v[nod].size();++i)
    {
        int vecin=v[nod][i];
        ++ed[cc];
        if(viz[vecin])
            continue;
        dfs(vecin);
    }
}
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    cin>>n>>m>>k;
    for(int i=1;i<=k;++i)
    {
        int nr;
        cin>>nr;
        gov.push_back(nr);
    }
    for(int i=1;i<=m;++i)
    {
        int a,b;
        cin>>a>>b;
        v[a].push_back(b);
        v[b].push_back(a);
    }
    int sol=0;
    int mx=0;
    for(int i=0;i<k;++i)
    {
        ++cc;
        dfs(gov[i]);
        ed[cc]/=2;
        if(sz[cc]>sz[mx])
            mx=cc;
    }
    for(int i=1;i<=n;++i)
        if(!viz[i])
        {
            cc=mx;
            int prev=ed[cc];
            dfs(i);
            int curr=ed[cc];
            ed[cc]=prev+(curr-prev)/2;
        }
    for(int i=1;i<=k;++i)
    {
        long long fr=sz[i]*(sz[i]-1)/2;
        sol=sol+fr-ed[i];
    }
    cout<<sol;
    return 0;
}


Comments

Submit
0 Comments
More Questions

Zoos
Build a graph
Almost correct bracket sequence
Count of integers
Differences of the permutations
Doctor's Secret
Back to School
I am Easy
Teddy and Tweety
Partitioning binary strings
Special sets
Smallest chosen word
Going to office
Color the boxes
Missing numbers
Maximum sum
13 Reasons Why
Friend's Relationship
Health of a person
Divisibility
A. Movement
Numbers in a matrix
Sequences
Split houses
Divisible
Three primes
Coprimes
Cost of balloons
One String No Trouble
Help Jarvis!